package com.businessportal.web.common;

import java.util.Calendar;
import java.util.Date;

/**
 * Created by Vadim on 9/18/14.
 */
public class AuthHelper {

    public static String generateCookieToken(String userName) throws Exception {
        Calendar cal = Calendar.getInstance();
        cal.setTime(new Date());
        cal.add(Calendar.MINUTE, 30);
        String cookieText = userName + "|" + DateTimeHelper.dateFormatForCalendar(cal.getTime());
        return CryptoHelper.getInstance().encrypt(cookieText);
    }

    public static boolean checkIfCookieValid(String userName, String cookieData) throws Exception {
        String decData = CryptoHelper.getInstance().decrypt(cookieData);
        String data [] = decData.split("\\|");

        if(data.length != 2)
            return false;

        Date cookieEndDate = DateTimeHelper.parseDateFromString(data[1]);

        if(!userName.equalsIgnoreCase(data[0]))
            return false;

        if(cookieEndDate.before(new Date()))
            return false;

        return true;
    }
}
